#include <rtthread.h>
#include "base.h" 
#include "rtconfig.h"
#include "rtdef.h"


/* 时间结构体 */
typedef struct
{
    int year;
    int month;
    int day;
    int hour;
    int minute;
    int second;
} time_info_t;

/* 共享时间结构体 */
static time_info_t shared_time = {2025, 1, 1, 0, 0, 0};

/* 互斥锁对象 */
static rt_mutex_t time_mutex = RT_NULL;

/* 写任务：更新时间 */
void time_update_thread(void *parameter)
{
    while (1)
    {
       rt_mutex_take(time_mutex, RT_WAITING_FOREVER);

        shared_time.second++;
        if (shared_time.second >= 60)
        {
            shared_time.second = 0;
            shared_time.minute++;
        }
        if (shared_time.minute >= 60)
        {
            shared_time.minute = 0;
            shared_time.hour++;
        }
        if (shared_time.hour >= 24)
        {
            shared_time.hour = 0;
            shared_time.day++;
        }

        // 此处略过月份与年份进位逻辑，保持简洁
        rt_mutex_release(time_mutex);
        rt_thread_mdelay(1);
    }
}

/* 读任务：打印当前时间 */
void time_read_thread(void *parameter)
{
    time_info_t local_time;

    while (1)
    {
        //rt_mutex_take(time_mutex, RT_WAITING_FOREVER);

        /* 读取共享时间到局部变量 */
        local_time = shared_time;

        //rt_mutex_release(time_mutex);

        rt_kprintf("[Reader] Time: %04d-%02d-%02d %02d:%02d:%02d\n",
                   local_time.year, local_time.month, local_time.day,
                   local_time.hour, local_time.minute, local_time.second);

        rt_thread_mdelay(10); 
    }
}

/* 初始化函数 */
int main(void)
{
    time_mutex = rt_mutex_create("time_mutex", RT_IPC_FLAG_PRIO);

    rt_thread_t tid_update = rt_thread_create("time_upd", time_update_thread, RT_NULL,
                                              1024, 10, 10);
    rt_thread_t tid_read = rt_thread_create("time_read", time_read_thread, RT_NULL,
                                            1024, 10, 10);

    if (tid_update) rt_thread_startup(tid_update);
    if (tid_read) rt_thread_startup(tid_read);

    return 0;
}